//
//  HomeViewController.m
//  RedManStock
//
//  Created by lanou3g on 15/7/21.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "HomeViewController.h"
#import "HeadButtonView.h"
#import "Scroll_PageControlView.h"
#import "HomePic.h"
#import "NiuRen.h"
#import "Analyst.h"
#import "AnalystViewPoints.h"
#import "Niu_AnalystTableViewCell.h"
#import "HeadControlView.h"
#import "AnalystHomeViewController.h"
#import "AnalystArticleViewController.h"
#import "StockHomeViewController.h"
#import "StockSearchResultTVC.h"
#import "MBProgressHUD.h"
@interface HomeViewController ()

@property (nonatomic,retain) Scroll_PageControlView *headScrollView;
@property (nonatomic,retain) HeadButtonView *headButtonView;
@property (nonatomic,retain) HeadControlView *headControlView;

//这两个是牛人的重要参数
@property (nonatomic,retain) NSString *moreDatePara;
@property (nonatomic,retain) NSString *moreIdPara;
//这两个是分析师的重要参数
@property (nonatomic,retain) NSString *analystMoreDatePara;
@property (nonatomic,retain) NSString *analystMoreIdPara;

@property (nonatomic,retain) NSMutableArray *lunboArray;
@property (nonatomic,retain) NSMutableArray *niuRenArray;
@property (nonatomic,retain) NSMutableArray *analystArray;
@property (nonatomic,assign) int niurenFlag;
@property (nonatomic,assign) int analystFlag;
@property (nonatomic,assign) int lunboFlag;
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    给一个状态，YES代表牛人，NO代表分析师荐股
    self.which=YES;
//    第一次进来,设置update为YES，从而走loadNewData的方法
    self.update=YES;
    
    _niurenFlag=0;
    _analystFlag=0;
    _lunboFlag=0;
    
//    导航栏右侧搜索按钮
    self.navigationItem.rightBarButtonItem = ({
        UIBarButtonItem *searchBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(clickSearchBBI:)];
        searchBarButtonItem;
    });
//    self.navigationItem.title = @"首页";
    self.navigationItem.titleView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 44)];
    UILabel *label=[UILabel labelWithFrame:self.navigationItem.titleView.bounds text:@"首页"];
    label.textColor=[UIColor whiteColor];
    label.font=[UIFont systemFontOfSize:17];
    label.textAlignment=NSTextAlignmentCenter;
    [self.navigationItem.titleView addSubview:label];
    self.navigationController.navigationBar.tintColor=MyGrayColor;
//    self.navigationController.navigationBar.translucent=NO;
    
//    分配内存
    self.lunboArray=[NSMutableArray array];
    self.niuRenArray=[NSMutableArray array];
    self.analystArray=[NSMutableArray array];
    
    self.tableView.tableHeaderView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 225)];
    self.tableView.tableHeaderView.backgroundColor=MyGrayColor;
#warning 测试(图片待续) - headView -
//    UIImage *image=[UIImage imageNamed:@"1431608058217"];
//    self.headScrollView=[[Scroll_PageControlView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 150) images:@[image,image,image]];
    self.headButtonView=[[HeadButtonView alloc]initWithFrame:CGRectMake(0, 150, [UIScreen mainScreen].bounds.size.width, 60)];
    
//    [self.tableView.tableHeaderView addSubview:self.headScrollView];
    [self.tableView.tableHeaderView addSubview:self.headButtonView];
    
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"Niu_AnalystTableViewCell" bundle:nil] forCellReuseIdentifier:@"Niu_AnalystTableViewCell"];
    
#warning 测试 headView
    
//    self.headControlView=[[HeadControlView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 30) titleArray:@[@"股精动态",@"分析师荐股"]];
//    for (int i=0; i<_headControlView.buttonArray.count; i++) {
//        UIButton *button=_headControlView.buttonArray[i];
//        [button addTarget:self action:@selector(buttonClickToChangeWhich:) forControlEvents:UIControlEventTouchUpInside];
//    }
//    [self.tableView addSubview:self.headControlView];
    
    
//    请求数据
    [self loadNewData];
}

#pragma mark - 点击搜索按钮
- (void)clickSearchBBI:(UIBarButtonItem *)rightBBI{
    
    StockSearchResultTVC *stockSearchTVC=[[StockSearchResultTVC alloc]init];
    UISearchController *searchController=[[UISearchController alloc]initWithSearchResultsController:stockSearchTVC];
    stockSearchTVC.searchController=searchController;
    [self presentViewController:searchController animated:YES completion:nil];
//    self.navigationController.navigationBar.translucent=YES;
}

- (void)setUpScoll_PageView{
    NSMutableArray *imageArray=[NSMutableArray array];
    UIImage *image=[UIImage imageNamed:@"community.png"];
    for (int i=0; i<self.lunboArray.count; i++) {
        [imageArray addObject:image];
    }
    self.headScrollView=[[Scroll_PageControlView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 150) images:imageArray];
    [self.view addSubview:self.headScrollView];
    
    for (int i=0; i<self.lunboArray.count; i++) {
        HomePic *homPic=self.lunboArray[i];
        UIButton *button=self.headScrollView.buttonArray[i];
        [button addTarget:self action:@selector(clickScoll_PageView:) forControlEvents:UIControlEventTouchUpInside];
        //button.imageView就得这么请求
        [button.imageView sd_setImageWithURL:[NSURL URLWithString:homPic.coverImageStr] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            [button setBackgroundImage:image forState:UIControlStateNormal];
        }];
    }
}

- (void)clickScoll_PageView:(UIButton *)button{
    
    NSInteger index=button.tag-4000;
    AnalystArticleViewController *analystArticleVC=[[AnalystArticleViewController alloc]init];
    HomePic *homePic=self.lunboArray[index];
    analystArticleVC.webUrl=homePic.urlStr;
    analystArticleVC.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:analystArticleVC animated:YES];
}


//- (void)viewWillAppear:(BOOL)animated{
//    if (self.update==YES) {
//        [self loadNewData];
//    }
//    self.update=NO;
//}

//首页轮播图
//http://api.gongniucaijing.com/Announcement/newindex?idfa=7B7C9B42-5C18-4EEB-A0F8-6708DE081AAE&machine=iPhone%205&os=iPhone%20OS%208.2&platform=1&protocolVersion=1.0&qudao=0000001&resolution=640%2A1136&token=d58f02522dac7e698a4600c8b18ff02c0b9fa6df&uuid=BULLSTOCK-79460017-C3E5-45EC-B98C-1DD541A61127&version=1.9.0&versionCode=190


//弄网址和参数
//请求数据
//解析，给数据源赋值，分情况
//endrefresh


//在下拉刷新中，三个网址都请求
-(void)loadNewData{
    
    
    //开启大菊花
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.yOffset=55;
    
#pragma 首页轮播图 - 暂时不用，到时候用其他的 -
    
#warning 到时候这里要开启
//    [self.lunboArray removeAllObjects];
//    [self.niuRenArray removeAllObjects];
//    [self.analystArray removeAllObjects];
    
    
    NSString *url=@"http://api.gongniucaijing.com/Announcement/newindex";
    
    [[MyHandle new] requestDataWithURLStr:url parameterBlock:^NSDictionary *{
        
        return nil;
        
    } successBlock:^(NSDictionary *responseDic) {
        NSArray *array1=[[responseDic objectForKey:@"data"] objectForKey:@"lists"];
        [self.lunboArray removeAllObjects];
        for (NSDictionary *dic in array1) {
            HomePic *homePic=[HomePic new];
            homePic.urlStr=[dic objectForKey:@"url"];
            homePic.coverImageStr=[dic objectForKey:@"coverimg"];
            [self.lunboArray addObject:homePic];
        }
        [self setUpScoll_PageView];
        
    } errorBlock:^(NSError *error) {
    }];
    
    
    //牛人
    //牛人荐股
    //http://api.gongniucaijing.com/trade/list?command=0&idfa=7B7C9B42-5C18-4EEB-A0F8-6708DE081AAE&machine=iPhone%205&number=20&offset=0&os=iPhone%20OS%208.2&platform=1&protocolVersion=1.0&qudao=0000001&resolution=640%2A1136&token=d58f02522dac7e698a4600c8b18ff02c0b9fa6df&type=niuren&uuid=BULLSTOCK-79460017-C3E5-45EC-B98C-1DD541A61127&version=1.9.0&versionCode=190
    
    NSString *url1=@"http://api.gongniucaijing.com/trade/list";
    
    [[[MyHandle alloc]init] requestDataWithURLStr:url1 parameterBlock:^NSDictionary *{
        
        NSDictionary *dic=@{@"number":@"20",
                            @"offset":@"0",
                            @"type":@"niuren"};
        return dic;
        
    } successBlock:^(NSDictionary *responseDic) {
        NSArray *array1=[[responseDic objectForKey:@"data"] objectForKey:@"lists"];
        
        NSArray *array2=[array1[0] objectForKey:@"lists"];
        
#warning 加载更多的时候的重要参数1: date,用self.moreDatePara接收，是第一次请求到的下面的数据
        self.moreDatePara=[[array1[0] objectForKey:@"date"] stringValue];
        
//      设置临时的数组
        NSMutableArray *tempArray=[NSMutableArray array];
        for (NSDictionary *myDic in array2) {
            
            NiuRen *niuren=[[NiuRen alloc]init];
            niuren.tradeSB=[NiuRenTrade new];
            niuren.memberSB=[NiuRenMember new];
            [niuren.tradeSB setValuesForKeysWithDictionary:(NSDictionary *)[myDic objectForKey:@"trade"]];
            [niuren.memberSB setValuesForKeysWithDictionary:(NSDictionary *)[myDic objectForKey:@"member"]];
            
#warning 加载更多的重要参数2: id，他是最后一trade里的id
            self.moreIdPara=niuren.tradeSB.niurenTrade_id;
            [tempArray addObject:niuren];
        }
        
        self.niuRenArray=tempArray;
#warning 两个不同的cell，这样真的好吗? - >还需要判断一下_which
        [self.tableView reloadData];
        
//结束大菊花
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        _niurenFlag=1;
        if (_niurenFlag==1 && _analystFlag==1) {
            [self.tableView.header endRefreshing];
            _niurenFlag=0;
            _analystFlag=0;
        }
        
    } errorBlock:^(NSError *error) {
        [self setUpMBProgressWithText:@"网络错误，请检查网络"];
    }];
    
    
    //分析师荐股
    //分析师荐股 viewpoint list 数据：直接拼接
    //http://api.gongniucaijing.com/viewpoint/list?command=0&idfa=7B7C9B42-5C18-4EEB-A0F8-6708DE081AAE&machine=iPhone%205&number=20&offset=0&os=iPhone%20OS%208.2&platform=1&protocolVersion=1.0&qudao=0000001&resolution=640%2A1136&token=d58f02522dac7e698a4600c8b18ff02c0b9fa6df&uuid=BULLSTOCK-79460017-C3E5-45EC-B98C-1DD541A61127&version=1.9.0&versionCode=190
    
    NSString *url2=@"http://api.gongniucaijing.com/viewpoint/list";
    [[[MyHandle alloc]init] requestDataWithURLStr:url2 parameterBlock:^NSDictionary *{
        NSDictionary *dic=@{@"number":@"20",
                            @"offset":@"0",
                            @"command":@"0"};
        return dic;
        
    } successBlock:^(NSDictionary *responseDic) {
        NSArray *array1=[[responseDic objectForKey:@"data"] objectForKey:@"lists"];
        
        NSArray *array2=[array1[0] objectForKey:@"lists"];
//分析师重要参数1
        self.analystMoreDatePara=[[array1[0] objectForKey:@"date"] stringValue];
        
        NSMutableArray *tempArray=[NSMutableArray array];
        for (NSDictionary *dic in array2) {
            
            Analyst *analyst=[[Analyst alloc]init];
            analyst.viewPointSB=[[AnalystViewPoints alloc]init];
            [analyst setValuesForKeysWithDictionary:[dic objectForKey:@"analyst"]];
            [analyst.viewPointSB setValuesForKeysWithDictionary:[dic objectForKey:@"viewpoint"]];
            
//分析师重要参数2
            self.analystMoreIdPara=analyst.viewPointSB.viewPoint_id;
            [tempArray addObject:analyst];
        }
        self.analystArray=tempArray;
        [self.tableView reloadData];
        
        _analystFlag=1;
        if (_niurenFlag==1 && _analystFlag==1) {
            [self.tableView.header endRefreshing];
            _niurenFlag=0;
            _analystFlag=0;
        }
        
    } errorBlock:^(NSError *error) {
    }];
    
    
}

//hud，文字
- (void)setUpMBProgressWithText:(NSString *)text{
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode=MBProgressHUDModeText;
    hud.labelText=text;
    [hud hide:YES afterDelay:1.5f];
}

- (void)loadMoreData{
    
    //牛人
    if (_which) {
        
        NSString *url1=@"http://api.gongniucaijing.com/trade/list";
        
        [[[MyHandle alloc]init] requestDataWithURLStr:url1 parameterBlock:^NSDictionary *{
            
            NSDictionary *dic=@{@"number":@"20",
                                @"offset":[NSString stringWithFormat:@"%lu",self.niuRenArray.count],
                                @"type":@"niuren",
                                @"command":@"1",
                                @"date":self.moreDatePara,
                                @"id":self.moreIdPara};
            
            return dic;
            
        } successBlock:^(NSDictionary *responseDic) {
            NSArray *array1=[[responseDic objectForKey:@"data"] objectForKey:@"lists"];
            
            NSArray *array2=[array1[0] objectForKey:@"lists"];
            
            NSMutableArray *tempArray=[NSMutableArray array];
            for (NSDictionary *myDic in array2) {
                
                NiuRen *niuren=[[NiuRen alloc]init];
                niuren.tradeSB=[NiuRenTrade new];
                niuren.memberSB=[NiuRenMember new];
                [niuren.tradeSB setValuesForKeysWithDictionary:(NSDictionary *)[myDic objectForKey:@"trade"]];
                [niuren.memberSB setValuesForKeysWithDictionary:(NSDictionary *)[myDic objectForKey:@"member"]];
#warning 加载更多时，该参数会变，也是最后一个trade的id值
                self.moreIdPara=niuren.tradeSB.niurenTrade_id;
                [tempArray addObject:niuren];
            }
#warning 两个不同的cell，这样真的好吗? - >还需要判断一下_which
            [self.niuRenArray addObjectsFromArray:tempArray];
            [self.tableView reloadData];
            [self.tableView.footer endRefreshing];
            
        } errorBlock:^(NSError *error) {
            [self setUpMBProgressWithText:@"网络错误，请检查网络"];
        }];
        
    }
    //分析师
    else{
        
        NSString *url2=@"http://api.gongniucaijing.com/viewpoint/list";
        [[[MyHandle alloc]init] requestDataWithURLStr:url2 parameterBlock:^NSDictionary *{
            NSDictionary *dic=@{@"number":@"20",
                                @"offset":[NSString stringWithFormat:@"%lu",self.analystArray.count],
                                @"command":@"1",
                                @"date":self.analystMoreDatePara,
                                @"id":self.analystMoreIdPara};
            return dic;
            
        } successBlock:^(NSDictionary *responseDic) {
            NSArray *array1=[[responseDic objectForKey:@"data"] objectForKey:@"lists"];
            
            NSArray *array2=[array1[0] objectForKey:@"lists"];
            
            NSMutableArray *tempArray=[NSMutableArray array];
            for (NSDictionary *dic in array2) {
                
                Analyst *analyst=[[Analyst alloc]init];
                analyst.viewPointSB=[[AnalystViewPoints alloc]init];
                [analyst setValuesForKeysWithDictionary:[dic objectForKey:@"analyst"]];
                [analyst.viewPointSB setValuesForKeysWithDictionary:[dic objectForKey:@"viewpoint"]];
                
                self.analystMoreIdPara=analyst.viewPointSB.viewPoint_id;
                [tempArray addObject:analyst];
            }
            [self.analystArray addObjectsFromArray:tempArray];
            [self.tableView reloadData];
            [self.tableView.footer endRefreshing];
            
        } errorBlock:^(NSError *error) {
        }];
        
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    self.headControlView= nil;
    if (_headControlView==nil) {
        _headControlView = [[HeadControlView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 30) titleArray:@[@"股精动态",@"分析师荐股"]];
//        _headButtonView.backgroundColor=[UIColor colorWithRed:0.702 green:0.747 blue:0.734 alpha:1.000];
        for (int i=0; i<_headControlView.buttonArray.count; i++) {
            UIButton *button=_headControlView.buttonArray[i];
            [button addTarget:self action:@selector(buttonClickToChangeWhich:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    if (_which) {
        self.headControlView.nowLocation=0;
    }
    else{
        self.headControlView.nowLocation=1;
    }
    return self.headControlView;
    
}

//区头的button点击事件
- (void)buttonClickToChangeWhich:(UIButton *)button{
    
    NSInteger index=button.tag-1000;
//    self.headControlView.nowLocation=index;
    
    if (index==0) {
        _which=YES;
    }
    else{
        _which=NO;
    }
    
    [self.tableView reloadData];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (_which) {
        return self.niuRenArray.count;
    }
    else{
        return self.analystArray.count;
    }
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
#warning 测试
    
    Niu_AnalystTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Niu_AnalystTableViewCell" forIndexPath:indexPath];
    
    if (_which) {
        //牛人
        NiuRen *niuren=self.niuRenArray[indexPath.row];
        cell.niuren=niuren;
        
        if (niuren.memberSB.avatarImage==nil) {
            [cell.avatarImageView sd_setImageWithURL:[NSURL URLWithString:niuren.memberSB.avatar] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                
                [cell.avatarButton setBackgroundImage:image forState:UIControlStateNormal];
                niuren.memberSB.avatarImage=image;
            }];
        }
#warning 因为用户的头像没有功能，而分析师有功能，而他俩公用一个cell上的button，所以这里要把用户交互关闭
        cell.avatarButton.userInteractionEnabled=NO;
        cell.moreButton.userInteractionEnabled=NO;
        [cell.avatarButton setBackgroundImage:niuren.memberSB.avatarImage forState:UIControlStateNormal];
        
    }
    else{
        //分析师
        Analyst *analyst=self.analystArray[indexPath.row];
        cell.analyst=analyst;
        if (analyst.avatarImage==nil) {
            [cell.avatarImageView sd_setImageWithURL:[NSURL URLWithString:analyst.avatar] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
               
                [cell.avatarButton setBackgroundImage:image forState:UIControlStateNormal];
                analyst.avatarImage=image;
                
#pragma mark  给cell的avatarButton 和 moreButton 添加事件
#warning 但你确定这里的位置一定对吗，应该是一定会走这个方法吧？！
                
                cell.avatarButton.tag=2000+indexPath.row;
                [cell.avatarButton addTarget:self action:@selector(ClickAnalystAvatar:) forControlEvents:UIControlEventTouchUpInside];
                
                cell.moreButton.tag=3000+indexPath.row;
                [cell.moreButton addTarget:self action:@selector(ClickAnalystMore:) forControlEvents:UIControlEventTouchUpInside];
                
            }];
        }
        cell.avatarButton.userInteractionEnabled=YES;
        cell.moreButton.userInteractionEnabled=YES;
        [cell.avatarButton setBackgroundImage:analyst.avatarImage forState:UIControlStateNormal];
    }
    
    
    return cell;
    
}

#pragma mark - cell上两个button添加的响应事件 -
//点击分析师头像，进入分析师详情页
- (void)ClickAnalystAvatar:(UIButton *)button{
    AnalystHomeViewController *analystHomeVC=[[AnalystHomeViewController alloc]initWithHeader:YES footer:YES];
    
    NSInteger index=button.tag-2000;
    analystHomeVC.analyst=self.analystArray[index];
//    UINavigationController *nVC=[[UINavigationController alloc]initWithRootViewController:analystHomeVC];
    analystHomeVC.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:analystHomeVC animated:YES];
    
}

//查看，跳到具体文章
- (void)ClickAnalystMore:(UIButton *)button{
    NSInteger index=button.tag-3000;
    AnalystArticleViewController *analystArticleVC=[[AnalystArticleViewController alloc]init];
    Analyst *analyst=self.analystArray[index];
    analystArticleVC.webUrl=analyst.viewPointSB.url;
    analystArticleVC.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:analystArticleVC animated:YES];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_which) {
        return 112+15;
    }
    else{
        return 88+15;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (_which) {
        NiuRen *niuren=self.niuRenArray[indexPath.row];
        StockHomeViewController *stockHomeVC=[[StockHomeViewController alloc]initWithHeader:NO footer:NO];
        stockHomeVC.stockName=niuren.tradeSB.stockSB.name;
        stockHomeVC.stockCode=niuren.tradeSB.stockSB.code;
        stockHomeVC.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:stockHomeVC animated:YES];
        
        
    }
    else{
        
        Analyst *anlyst=self.analystArray[indexPath.row];
        StockHomeViewController *stockHomeVC=[[StockHomeViewController alloc]initWithHeader:NO footer:NO];
        stockHomeVC.stockName=anlyst.viewPointSB.stockSB.name;
        stockHomeVC.stockCode=anlyst.viewPointSB.stockSB.code;
        stockHomeVC.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:stockHomeVC animated:YES];
        
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}





/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
